'use strict';

module.exports = options => {
  return async (ctx, next) => {
    // 登录token
    const { dauthorization } = ctx.request.header;
    const { userToken } = ctx.session;
    if (userToken && dauthorization === userToken) {
      try {
        // 解码token
        const decode = await ctx.app.jwt.verify(dauthorization, options.secret);// 验证token
        // 获取用户信息
        ctx.session.userInfo = decode;
      } catch (error) {
        ctx.status = 401;
        ctx.body = {
          code: 1,
          message: error.message,
        };
        return;
      }
      // 切记先解析token并存储数据后再执行回调，否则解析数据获取不到x
      await next();
    } else {
      ctx.status = 401;
      ctx.body = {
        code: 1,
        message: '请登录',
      };
      return;
    }
  };
};
